package com.logos.musicframe.service;


import com.alibaba.fastjson.JSON;
import com.logos.musicframe.adapter.StorageAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileService {

    private final StorageAdapter storageAdapter;

    public FileService(StorageAdapter storageAdapter) {
        this.storageAdapter = storageAdapter;
    }

    /**
     * 列出所有桶
     */
    public List<String> getAllBucket() {
        return storageAdapter.getAllBucket();
    }

    /**
     * 获取文件路径
     */
    public String getUrl(String bucketName, String objectName) {
        return storageAdapter.getUrl(bucketName, objectName);
    }

    public String uploadFile(byte[] uploadFile, String bucket, String objectName) {
        // 获取原始文件名的后缀
        String extension = objectName.substring(objectName.lastIndexOf("."));
        // 得到新的文件名
        objectName = UUID.randomUUID() + extension;
        storageAdapter.uploadFile(uploadFile, bucket, objectName, objectName);
        return storageAdapter.getUrl(bucket, objectName);
    }

    public String uploadFile(File file) {
        try {
            if(log.isInfoEnabled()){
                log.info("FileService.uploadFile.file: {}", JSON.toJSONString(file));
            }
            String fileName = file.getName();
            String[] avatarImageArr = fileName.split("\\\\");
            fileName = avatarImageArr[avatarImageArr.length - 1];
            byte[] fillBytes = Files.readAllBytes(file.toPath());
            // 根据文件后缀判断存放哪个bucket
            if (fileName.endsWith(".mp3")) {
                return this.uploadFile(fillBytes, "music", fileName);
            }else if(fileName.endsWith(".jpg") || fileName.endsWith(".png")){
                return this.uploadFile(fillBytes, "image", fileName);
            }else if(fileName.endsWith(".lrc")){
                return this.uploadFile(fillBytes, "lrc", fileName);
            }else{
                return this.uploadFile(fillBytes, "other", fileName);
            }
        } catch (Exception e) {
            log.error("FillService.uploadFile.error: {}", e.getMessage(), e);
            return null;
        }
    }
}
